//
//  DeviceManagerViewController.m
//  ZhangJiangJun
//
//  Created by FENGYL on 2017/1/17.
//  Copyright © 2017年 FENGYL. All rights reserved.
//

#import "DeviceManagerViewController.h"
#import "UserModel.h"
#import "DeviceManagerTableViewCell.h"
#import "NetworkCommand.h"

#import <MJRefresh.h>
#import <MBProgressHUD.h>
#import <ZRQRCodeViewController.h>
#import <AVFoundation/AVFoundation.h>

@interface DeviceManagerViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (weak, nonatomic) IBOutlet UIBarButtonItem *editBarButtonItem;
@property (weak, nonatomic) IBOutlet UITableView *deviceManagerTableView;
@property (weak, nonatomic) IBOutlet UILabel *deviceManagerLabel;
@property (weak, nonatomic) IBOutlet UILabel *deviceNumberLabel;
@property (weak, nonatomic) IBOutlet UILabel *deviceNameLabel;

@property (strong, nonatomic) UserModel * userModel;

@end

@implementation DeviceManagerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setUpUI];
    
    self.deviceManagerTableView.delegate = self;
    self.deviceManagerTableView.dataSource = self;
}

-(void)setUpUI{
    
    //UserModel
    self.userModel = [[UserModel alloc]init];
    
    //编辑按钮
    [self.editBarButtonItem setTitle:NSLocalizedString(LOCALIZABLE_EDIT, nil)];
    [self.editBarButtonItem setTintColor:[UIColor clearColor]];
    
    //去掉多余横线
    self.deviceManagerTableView.tableFooterView = [[UIView alloc]init];
 
    //设备管理label
    [self.deviceManagerLabel setText:NSLocalizedString(LOCALIZABLE_DEVICE_MANAGER, nil)];
    
    //设备号label
    [self.deviceNumberLabel setText:NSLocalizedString(LOCALIZABLE_DEVICE_NUMBER, nil)];
    
    //设备名label
    [self.deviceNameLabel setText:NSLocalizedString(LOCALIZABLE_DEVICE_NAME, nil)];
    
    //下拉刷新
    self.deviceManagerTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        [NetworkCommand getDeviceListSuccess:^{
            
            if (!self.userModel.deviceByAccountArray) {
                
                NSDictionary * dict = self.userModel.deviceByAccountArray[0];
                
                self.userModel.currentDeviceName = [dict objectForKey:NC_DISPLAY_NAME];
                
            }
            
            [self.deviceManagerTableView reloadData];
            
            [self.deviceManagerTableView.mj_header endRefreshing];
            
        } failure:^{
            
            MBProgressHUD * hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            
            [hud.label setText:NSLocalizedString(LOCALIZABLE_REFRESHING_FAILED, nil)];
            
            hud.mode = MBProgressHUDModeCustomView;
            
            hud.removeFromSuperViewOnHide = YES;
            
            [hud hideAnimated:YES afterDelay:0.5];
            
            [self.deviceManagerTableView.mj_header endRefreshing];
            
        }];
        
    }];
    
    //刷新列表
    if (!self.userModel.deviceByAccountArray) {
        
        [self.deviceManagerTableView.mj_header beginRefreshing];
        
        
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark 添加设备
- (IBAction)addNewDevice:(id)sender {
    
    if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_7_1) {
        // Pre iOS 8 -- No camera auth required.
        
    }else {
        // iOS 8 后，全部都要授权
        
        // Thanks: http://stackoverflow.com/a/24684021/2611971
        
        AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        switch (status) {
            case AVAuthorizationStatusNotDetermined:{
                // 许可对话没有出现，发起授权许可
                
                [self cameraAllow];
                
                [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                    
                    if (granted) {
                        //第一次用户接受

                        
                    }else{
                        //用户拒绝
                        return;
                    }
                }];
                break;
            }
            case AVAuthorizationStatusAuthorized:{
                // 已经开启授权，可继续
                
                [self qrcodeScanning];
                
                break;
            }
            case AVAuthorizationStatusDenied:
            case AVAuthorizationStatusRestricted:
                // 用户明确地拒绝授权，或者相机设备无法访问
                
                [self cameraAllow];
                
                break;
            default:
                break;
        }
        
    }
    
    
    
    
    
}

#pragma mark 相机许可
-(void)cameraAllow{
    
    UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"用户未允许开启相机服务" message:@"请手动开启相机" preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction * confirmAction = [UIAlertAction actionWithTitle:@"去设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        if ([[UIApplication sharedApplication] canOpenURL:url])
        {
            [[UIApplication sharedApplication] openURL:url];
            
        }
        
    }];
    
    UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    [alertController addAction:confirmAction];
    [alertController addAction:cancelAction];
    
    [self presentViewController:alertController animated:YES completion:nil];

    
}

#pragma mark 打开二维码扫描
-(void)qrcodeScanning{
    
    ZRQRCodeViewController *qrCode = [[ZRQRCodeViewController alloc] initWithScanType:ZRQRCodeScanTypeReturn];
    qrCode.qrCodeNavigationTitle = @"QR Code Scanning";
    
    [qrCode QRCodeScanningWithViewController:self completion:^(NSString *strValue) {
        
        NSLog(@"strValue = %@ ", strValue);
        if([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:strValue]]){
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:strValue]];
        } else {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Ooooops!" message:[NSString stringWithFormat:@"The result is %@", strValue] delegate:nil cancelButtonTitle:@"Cancel" otherButtonTitles:nil, nil];
            [alertView show];
        }
        
    } failure:^(NSString *message) {
        
    }];
    
}

#pragma mark TableView
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.userModel.deviceByAccountArray.count;
    
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSDictionary * deviceDict = self.userModel.deviceByAccountArray[indexPath.row];
    
    DeviceManagerTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"DeviceManagerTableViewCell"];
    
    if (cell == nil) {
        
        cell = [[DeviceManagerTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"DeviceManagerTableViewCell"];
        
    }
    
    [cell setCellDeviceNumber:[deviceDict objectForKey:NC_SERIAL_NUMBER ] deviceName:[deviceDict objectForKey:NC_DISPLAY_NAME]];
    
    
    if ([cell.cellDeviceSerialNumber isEqualToString:self.userModel.currentDeviceSerialNumber]) {
        
        [cell setBackgroundColor:[UIColor yellowColor]];
        
    }else{
        
        [cell setBackgroundColor:[UIColor clearColor]];
        
    }
    
    return cell;
    
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    //选择这个cell
    
    DeviceManagerTableViewCell * cell = [tableView cellForRowAtIndexPath:indexPath];
    
    self.userModel.currentDeviceSerialNumber = cell.cellDeviceSerialNumber;
    
    self.userModel.currentDeviceName = cell.cellDeviceName;
    
    [tableView reloadData];
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
